import difflib
import sys

"""difflib的练习"""


def writeText(src_file, dic_file):
    "写入_info信息到对应filename里"
    src_info = """text1:
    this module python difflib.
    hello python
    tvchen"""
    with open(src_file, 'w') as f:
        f.write(src_info)
    with open(src_file) as fs:
        print(fs.read())
    dic_info = """text2:
    this module python difflib.
    hello python
    tvchen"""
    with open(dic_file, 'w') as f:
        f.write(dic_info)
    with open(dic_file) as fs:
        print(fs.read())


def diff_cmd(src_file, dic_file):
    "读取文件，从文件里内容进行difflib ,要在命令行里面使用py -3 diffFile.py >demo.html"
    # src_file ="3.txt"
    # dic_file ="4.txt"
    with open(src_file) as src_f:
        src_text = src_f.read()
    with open(dic_file) as dic_f:
        dic_text = dic_f.read()

    src_text_lines = src_text.splitlines()  # src_f.read().splitlines()
    dic_text_lines = dic_text.splitlines()
    d = difflib.Differ()
    diff = d.compare(src_text_lines, dic_text_lines)
    print("\n".join(list(diff)))
    htmlrp = difflib.HtmlDiff()
    return htmlrp.make_file(src_text_lines, dic_text_lines)
    # print(diff.make_file(src_text_lines,dic_text_lines))


"diff_cmd('3.txt', '4.txt')"


def readfile(filename):
    "读取文件"
    try:
        with open(filename, 'r')as fileHandle:
            text = fileHandle.read().splitlines()
        # fileHandle =open(filename,'rb')
        # text =fileHandle.read().splitlines()
        return text
    except IOError as error:
        print("Error" + str(error))
        sys.exit()


"在命令行里输入py -3 diffFile.py 3.txt 4.txt >testreport2.html 生成报告"


def diff_syscmd():
    try:
        src_file = sys.argv[1]
        dic_file = sys.argv[2]
    except Exception as e:
        print("error" + str(e))
        print("Usage:diffFile.py src_file dic_file >testreport.html")
        sys.exit()

    if src_file == "" or dic_file == "":
        print("Usage:diffFile.py src_file dic_file >testreport.html")
        sys.exit()
    src_lines = readfile(src_file)
    dic_lines = readfile(dic_file)

    diff = difflib.HtmlDiff()
    print(diff.make_file(src_lines, dic_lines))


diff_syscmd()
